<template>
  <div class="wavesurfer-comp">
    <div id="waveform"></div>
    <div id="waveform2"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted } from "vue";
import WaveSurfer from "wavesurfer.js";
import RegionsPlugin from "wavesurfer.js/dist/plugins/regions.esm.js";

const regions = RegionsPlugin.create();
let activeRegion;
regions.on("region-clicked", (region, e) => {
  e.stopPropagation(); // prevent triggering a click on the waveform
  activeRegion = region;
  region.play(true);
  region.setOptions({ color: randomColor() });
});

// Give regions a random color when they are created
const random = (min, max) => Math.random() * (max - min) + min;
const randomColor = () =>
  `rgba(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)}, 0.5)`;

onMounted(() => {
  const ws = WaveSurfer.create({
    container: "#waveform",
    url: "/superman.mp3",
    mediaControls: true,
    plugins: [regions],
  });
  ws.on("decode", () => {
    console.log("decode");
    // console.log(regions.addRegion);

    regions.addRegion({
      start: 0,
      end: 8,
      content: "Resize me",
      color: randomColor(),
      drag: false,
      resize: true,
    });
    console.log("addRegion complete");

    // 测试
    console.log(1)
    const originalBuffer = ws.backend.buffer;
    const sampleRate = originalBuffer.sampleRate;
    console.log(2)
    const startTime = 10
    const endTime = 20
    const startSample = Math.floor(startTime * sampleRate);
    const endSample = Math.floor(endTime * sampleRate);
    const segmentLength = endSample - startSample;

    const newBuffer = new AudioContext().createBuffer(
      originalBuffer.numberOfChannels,
      segmentLength,
      sampleRate
    );

    for (let i = 0; i < originalBuffer.numberOfChannels; i++) {
      const channelData = originalBuffer.getChannelData(i);
      newBuffer.copyToChannel(channelData.subarray(startSample, endSample), i);
    }

    const wavBlob = bufferToWav(newBuffer); // 需实现 WAV 编码函数
    const clipPlayer = WaveSurfer.create({ container: "#waveform2" });
    clipPlayer.loadBlob(wavBlob);
  });
});
</script>
